<?php

namespace App\Http\Controllers\Admin;

use App\Http\Util\Err;
use App\Http\Util\HomeTool;
use App\Http\Util\Upload;
use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\ContractClass;
use App\Models\NewSearch;
use App\Models\OpenSearch;
use App\services\ImmService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;
use App\Jobs\UploadTask;

class UploadController extends Controller
{
    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * 上传图片并生成缩略图
     */
    public function saveImg()
    {
        try {
            $inputData = request()->all();
            $upload = new Upload();
            $url = $upload->upload($inputData, 'image');
            if ($url) {
                return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功', 'data' => $url]);
            } else {
                return response()->json(['code' => 1001, 'msg' => '上传失败']);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function saveZip(){
        try {
            $inputData = request()->all();
            $upload = new Upload();
            $url = $upload->uploadZip($inputData);
            if ($url) {
                return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功', 'data' => $url]);
            } else {
                return response()->json(['code' => 1001, 'msg' => '上传失败']);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function baseZip(){
        try {
            $inputData = request()->all();
            $upload = new Upload();
            $url = $upload->uploadZip($inputData);
            if ($url) {
                return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功', 'data' => $url]);
            } else {
                return response()->json(['code' => 1001, 'msg' => '上传失败']);
            }
        } catch (\Exception $e) {
            throw $e;
        }
    }


    public function baseImg(Request $request)
    {
        try {
            $disk = Storage::disk('oss');
            $file =$request->file('file');
            $date_path = date("Ymd",time());
            $path = $disk->put('/img/'.$date_path , $file);
            $url['url'] = config('site.oss_path').$path;
            $url['thumb'] = config('site.oss_path').$path;
            if ($url) {
                return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功', 'data' => $url]);
            } else {
                return response()->json(['code' => 1001, 'msg' => '上传失败']);
            }
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => '上传失败']);
        }
    }

    /**上传背景图
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function backImg()
    {
        try {
            $inputData = request()->all();
            $upload = new Upload();
            $file = $inputData['file'];
            //原文件名
            $originalName = $file->getClientOriginalName();
            //扩展名
            $ext = $file->getClientOriginalExtension();
            $type = $file->getClientMimeType();
            //临时绝对路径
            $realPath = $file->getRealPath();
            $date = date('Y-m-d',time());
            $filename = 'login'.'.'.$ext;
            if(file_exists('/upload/image/'.$filename)){
                unlink('/upload/image/'.$filename);
            }
            Storage::disk('image')->put($filename,file_get_contents($realPath));
            $data['url']  = '/upload/image/'.$filename;
            Redis::set('BACK_IMAGE_URL',$data['url']);
            return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功', 'data' => $data]);
        } catch (\Exception $e) {
            throw $e;
        }
    }


    public function audio(Request $request)

    {

        if ($request->hasFile('file')) {

            $file = $request->file('file'); // 获取上传的文件

            $originalName = $file->getClientOriginalName(); // 文件原名

            $ext = $file->getClientOriginalExtension();
            $name = date('Y-m-d',time()).'/'.uniqid().'.'.$ext;
            $realPath = $file->getRealPath(); //临时文件的绝对路径


            Storage::disk('audio')->put($name, file_get_contents($realPath)); // 文件名称 ， 内容

            return response()->json(['msg'=>'上传成功','url' => '/upload/audio/' . $name,'code'=>200,'name'=> $name]);

        } else {

            return response()->json(['msg'=>'上传失败','code'=>201]);

        }

    }

    /**上传到oss云存储
     * @param Request $request
     * @return void
     */
    public function uploadOss(Request $request)
    {

        $class_id = $request->get('class_id');
        $special_id = $request->get('special_id');
        if($special_id == 'undefined'){
            $special_id = 0;
        }
        if(!$class_id ){
            return response()->json(['msg'=>'请先选择分类','code'=>1001]);
        }
        $check_roles = HomeTool::checkRoles(91,'add');
        if(!$check_roles){
            return response()->json(['code' => 1001, 'msg' => '暂无此操作权限']);
        }
//        try{
            $class_id = json_decode($class_id);
            if(!is_array($class_id)){
                return response()->json(['msg'=>'请先选择分类','code'=>1001]);
            }
            $data['class_id'] =array_pop($class_id);
            $disk = Storage::disk('oss');
            $file = $request->file('file');
            $ext = $file->getClientOriginalExtension();
            if($ext != 'doc' && $ext != 'docx'){
              return response()->json(['msg'=>'只能上传doc和docx文件','code'=>1001]);
          }
            $uid = uuid();
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $notify = $http_type.$_SERVER['HTTP_HOST'];
            $post_data = [
                'file' => new \CURLFile(realpath($file->getRealPath())),
                'type' => $ext,
                'outtype' => 1,
                'callbackurl' =>  $notify.'/api/handle_pic?uid='.$uid
            ];
            $api = "http://all2img.ali.duhuitech.com/v1/convert_post";
            $header= 'aca9dd600912417f8f3ec7e02c101228';
            $rt = HomeTool::getCurl($api,$header,$post_data);
            $rt = json_decode($rt,true);
            if($rt['code'] != 10000)
            {
                return response()->json(['msg'=>'上传失败！请稍后重试','code'=>1001]);
            }
            $data['convert_token'] = $rt['result']['token'];
            $data['uid'] =  $uid;
            $data['size'] = ImmService::getFilesize($file->getSize());
            //原文件名
            $originalName = $file->getClientOriginalName();
            $data['title']=str_replace(strrchr($originalName, "."),"",$originalName);
            if (strpos($data['title'], '_') !== false) {
                $start = strpos($data['title'],"_");
                $data['title'] = mb_substr($data['title'],$start+1);
            }
            $date_path = date("Ymd",time());
            $path = $disk->put('/doc/'.$date_path , $file);
            if($path){
//                $pathArr = explode("/",$path);
//                $png_path = $pathArr[(count($pathArr)-1)];
//                $pngStr=str_replace(strrchr($png_path, "."),"",$png_path);
//                $png_path = 'img/' .$date_path.'/'.$pngStr;
                //返回存储到oss到地址
//                $SrcUri = config("site.imm_path") . $path;
//                $TgtUri = config("site.imm_path") . $png_path;
//                ImmService::docToPng($SrcUri,$TgtUri);
               $ext = explode('.',$path);
               $data['ext'] = end($ext);
               $data['path'] = config('site.oss_path').$path;
               $data['special_id'] = $special_id??0;
                if($ConModel =  Contract::create($data)){
//                    $search = new NewSearch();
//                    $data['id'] = $ConModel->id;
//                    $openAdd[]= $data;
//                    $search->add($openAdd);
//                    $task['id'] = $ConModel->id;
//                    $task['path'] = $path;
//                    $task['date_path'] =  $date_path;
//                    $task['title'] = $data['title'];
//                    dispatch(new UploadTask($task))->delay(now()->addSeconds(30));
                    return response()->json(['code' => Err::SUCCESS[0], 'msg' => '上传成功']);
                }
            }
            return response()->json(['msg'=>'上传失败！请稍后重试','code'=>1001]);
//        }catch (\Exception $e){
//            echo $e->getMessage();
//        }
    }

    /**生成图片回调接口
     * @param Request $request
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function handlePic(Request $request){
        $params = request()->post();
        $uid = request()->get('uid');
        dispatch(new UploadTask($uid,$params))->onQueue('contract');
    }


    public function uploadDoc(Request $request){
        $disk = Storage::disk('oss');
        $file = $request->file('file');
        $date_path = date("Ymd",time());
        $path = $disk->put('/constom/'.$date_path , $file);
        $data['url'] = config('site.oss_path').$path;
        $data['name'] = $path;
        $data['uid'] = time();
        return response()->json(['msg'=>'上传成功','data' =>$data]);
    }


    public function thumb_oss(Request $request){
        $config = [
            'accessId' => config('site.accessKeyId'),
            'accessKey' => config('site.accessSecret'),
            'endpoint' => config('site.point'),
            'bucket' => config('site.bucket')
        ];
        $ossClient = new OssClient($config['accessId'], $config['accessKey'], $config['endpoint']);
        $page = request()->get('page');
        $list = Contract::orderBy('id', 'desc')
            ->where(function ($query) use ($page) {
                $query->where('title_pic', 'like',  $page.'%');
            })
            ->limit(500)
            ->get(['id','title_pic'])->toArray();
        foreach($list as $k => $v){
            $img_path = 'thumb/'.uniqid().'.jpg';
            if($v['title_pic']){
                $result = $ossClient->uploadFile($config['bucket'],$img_path, public_path($v['title_pic']));
                if ($result['info']) {
                   Contract::where('id',$v['id'])->update(['title_pic'=>$result['info']['url']]);
                }
            }
        }
    }


    public function test(Request $request){
        $thumb = Upload::makeThumb();
    }
}
